package top.zackyoung.thirdlogin.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZackYoung
 * @version 1.0
 * @description
 * @date 2021/6/5 22:46
 */
public class HttpClientUtil {
    /**
     * @param param 只处理access_token=7c76186067e20d6309654c2bcc1545e41bac9c61&scope=&token_type=bearer
     * @return map
     */
    public static Map<String, String> params2Map(String param) {
        Map<String, String> map = new HashMap<>();
        Arrays.stream(param.split("&")).forEach(x -> {
            String[] split = x.split("=");
            map.put(split[0], split.length==2 ? split[1] : null);
        });
        return map;
    }

    public static String executeByMethod(Method method, String url, String param, boolean isProxy) {
        Proxy proxy = isProxy ?
                new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 10808)) : null;
        return method.equals(Method.GET) ? HttpRequest.get(url+"?"+param).setProxy(proxy).execute().body()
                : HttpRequest.post(url+"?"+param).setProxy(proxy).execute().body();
    }

    public static String get(String url, String param, boolean isProxy) {
        return executeByMethod(Method.GET, url, param, isProxy);

    }

    public static String get(String url, String param) {
        return get(url, param, false);

    }

    public static String post(String url, String param, boolean isProxy) {
        return executeByMethod(Method.POST, url, param, isProxy);
    }

    public static String post(String url, String param) {
        return post(url, param, false);
    }
}
